package cn.anc.aonicardv.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import cn.anc.aonicardv.MyApplication;

/**
 * Created by yangdai on 2017/7/13.
 */

public class NetUtils {

    /**
     * 是否连接记录仪
     *
     * @return
     * @
     */
    public static boolean isConnectedDevices(Context context) {
        if (MyApplication.IPHeader != null && DeviceUtils.isLingKeDevices(MyApplication.wifiSSID)) {
            return true;
        }
        return false;
    }
    /**
     * 获取SSID
     *
     * @return WIFI 的SSID
     */
    public static String getWIFISSID(Context context) {
        String ssid = "unknown ssid";

        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
            ConnectivityManager connManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) {
                if (networkInfo.getExtraInfo() != null) {
                    return networkInfo.getExtraInfo().replace("\"", "");
                }
            }
        } else {
            WifiManager mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (mWifiManager != null) {
                WifiInfo info = mWifiManager.getConnectionInfo();
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                    return info.getSSID();
                } else {
                    return info.getSSID().replace("\"", "");
                }
            }
        }

        return ssid;
    }

    /**
     * 判断移动网络是否连接成功！
     *
     * @param context 上下文环境
     * @return 判断结果
     */
    public static boolean isNetContected(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileNetworkInfo.isConnected()) {

            Log.i(Thread.currentThread().getName(), "isNetContected");
            return true;
        }
        Log.i(Thread.currentThread().getName(), "isNetDisconnected");
        return false;

    }




    /**
     * 设置手机的移动数据
     */
    public static boolean setMobileDataEnabled(Context context, boolean enabled){
        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        Method setMobileDataEnabl;
        try {
            LogUtil.e("llcTest1019","设置手机的移动数据 11111: ");
            setMobileDataEnabl = tm.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
            LogUtil.e("llcTest1019","设置手机的移动数据 222: ");
            if (null!=setMobileDataEnabl){
                setMobileDataEnabl.invoke(tm, enabled);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e("llcTest1019","移动数据设置错误: " + e.toString());
        }
        return false;
    }

    /**
     * 判断移动网络是否开启
     *
     * @return
     */
    public static boolean getMobileDataStatus(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        try {
            Method getMobileDataEnableMethod = telephonyManager.getClass().getDeclaredMethod("getDataEnabled");
            if (null!=getMobileDataEnableMethod){
                return (boolean)getMobileDataEnableMethod.invoke(telephonyManager);
            }
        } catch (Exception e) {
            LogUtil.e("llcTest1019","-------getMobileDataStatus Exception:"+e.getMessage());
            e.printStackTrace();
        }
        return false;
    }



    /**
     * 版本为6以上
     *
     * @return
     * @
     */
    public static boolean isVersionM() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return true;
        }
        return false;
    }
    /**
     * 判断当前网络是否可用(通用方法)
     * 耗时12秒
     * @return
     */
    public static boolean isNetPingUsable(){
        Runtime runtime = Runtime.getRuntime();
        try {
            Process process = runtime.exec("ping -c 3 www.baidu.com");
            int ret = process.waitFor();
            if (ret == 0){
                return true;
            }else {
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 判断当前网络是否可用(6.0以上版本)
     * 实时
     * @param context
     * @return
     */
    public static boolean isNetSystemUsable(Context context){
        boolean isNetUsable = false;
        ConnectivityManager manager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            NetworkCapabilities networkCapabilities =
                    manager.getNetworkCapabilities(manager.getActiveNetwork());
            isNetUsable = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
        }
        return isNetUsable;
    }

    /**
     * 判断是否有网络连接
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
    public static boolean getNetwork(Context context) {
        if (!NetUtils.isNetworkConnected(context)) {
            return true;
        }
        if (NetUtils.isWifiConnected(context)&& !NetUtils.isVersionM()) {
            return true;
        }
        return false;
    }


    /**
     * 判断WIFI网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isWifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    public static String getMobileIP() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("哎呀，出错了...", ex.toString());
        }
        return null;
    }



    /**
     * 判断MOBILE网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isMobileConnected(Context context) {
        TelephonyManager telephonyService = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            Method getDataEnabled = telephonyService.getClass().getDeclaredMethod("getDataEnabled");
            if (null != getDataEnabled) {
                return (Boolean) getDataEnabled.invoke(telephonyService);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取当前网络连接的类型信息
     *
     * @param context
     * @return
     */
    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }
    /**
     * 获取运营商名字
     *
     * @param context context
     * @return int
     */
    public static String getOperatorName(Context context) {
        /*
         * getSimOperatorName()就可以直接获取到运营商的名字
         * 也可以使用IMSI获取，getSimOperator()，然后根据返回值判断，例如"46000"为移动
         * IMSI相关链接：http://baike.baidu.com/item/imsi
         */
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        // getSimOperatorName就可以直接获取到运营商的名字
        return telephonyManager.getSimCountryIso();
    }


    /**
     * 获取当前的网络状态 ：没有网络0：WIFI网络1：3G网络2：2G网络3
     *
     * @param context
     * @return
     */
    public static int getAPNType(Context context) {
        int netType = 0;
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;// wifi
        } else if (nType == ConnectivityManager.TYPE_MOBILE) {
            int nSubType = networkInfo.getSubtype();
            TelephonyManager mTelephony = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                    && !mTelephony.isNetworkRoaming()) {
                netType = 2;// 3G
            } else {
                netType = 3;// 2G
            }
        }
        return netType;
    }

    public static String getLocalIpAddress() {
        try {
            for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = (NetworkInterface) en.nextElement();
                for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("here", ex.toString());
        }
        return "0.0.0.0";//dbb20180103 avoid causing hang for null point
    }

    public static String getWifiIpAddress(Context context) {
        try {

            // 只获取wifi地址
            WifiManager wifiManage = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);//获取WifiManager

            if (wifiManage == null||!wifiManage.isWifiEnabled()) {
                return "";
            }
            WifiInfo wifiInfo = wifiManage.getConnectionInfo();
            if (wifiInfo == null) {
                return "";
            }
            int paramInt = wifiInfo.getIpAddress();
            if (paramInt == 0) {
                return "";
            }
            return (paramInt & 0xFF) + "." + (0xFF & paramInt >> 8) + "." + (0xFF & paramInt >> 16) + "."
                    + (0xFF & paramInt >> 24);
        } catch (Exception ex) {
            Log.e("here", ex.toString());
        }
        return "";
    }




}
